package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApReadFollowMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApReadFollowService;
import com.usian.model.behavior.dtos.ReadBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApReadBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadFollowServiceImpl extends ServiceImpl<ApReadFollowMapper, ApReadBehavior> implements ApReadFollowService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //判断参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdAndEquipmentId(AppThreadLocalUtils.getUser().getId(), dto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(502,"行为实体不存在");
        }
        //查询ap_read_behavior表的数据
        ApReadBehavior apReadBehavior = getOne(Wrappers.<ApReadBehavior>lambdaQuery().eq(ApReadBehavior::getArticleId, dto.getArticleId()).eq(ApReadBehavior::getEntryId, apBehaviorEntry.getId()));
        if (apReadBehavior==null){//如果为null说明第一次阅读就创建并保存
            ApReadBehavior apReadBehavior1 = new ApReadBehavior();
            apReadBehavior1.setArticleId(dto.getArticleId());
            apReadBehavior1.setEntryId(apBehaviorEntry.getId());
            apReadBehavior1.setCount(1);
            apReadBehavior1.setReadDuration(dto.getReadDuration());
            apReadBehavior1.setPercentage(dto.getPercentage());
            apReadBehavior1.setLoadDuration(dto.getLoadDuration());
            apReadBehavior1.setCreatedTime(new Date());
            apReadBehavior1.setUpdatedTime(new Date());
            save(apReadBehavior1);
        }else {//说明是第n次阅读
            apReadBehavior.setCount(apReadBehavior.getCount()+1);
            apReadBehavior.setUpdatedTime(new Date());
            updateById(apReadBehavior);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
